
/*
 * ****************************
 * Eric Doherty
 * Jesse Kinney
 * 
 * TCSS 422 Scheduler simulator
 * Consumer Process Class
 * 
 * 6/4/08
 * ****************************
 */

public class Consumer extends Process
{
  private MemoryLocation mem;

  private boolean blocked;

  public Consumer(MemoryLocation m)
  {
    mem = m;
    blocked = false;
  }

  public void doInstruction()
  {
    blocked = false;
    consume();
  }

  public void consume()
  {
    downFull();
    if (!blocked)
    {
      downCrit();
      if (!blocked)
      {
        System.out.println("Process " + getPid() + " Consuming");
        mem.setMemoryLocation(mem.getData() - 1);
        upCrit();
        upEmpty();

        setChanged();
        notifyObservers(new Event(Event.EventTypes.UNBLOCKP));
      }
    }
  }

  private void downFull()
  {
    if (mem.getFull() == false)
    {
      System.out.println("Process " + getPid() + " blocks on full mutex");
      blocked = true;
      setChanged();
      notifyObservers(new Event(Event.EventTypes.FULL));
    }
    else
    {
      System.out.println("Process " + getPid() + " downs full mutex");
      mem.setFull(false);
    }
  }

  private void downCrit()
  {
    if (mem.getCrit() == false)
    {
      System.out.println("Process " + getPid() + " blocks on crit mutex");
      blocked = true;
      setChanged();
      notifyObservers(new Event(Event.EventTypes.CRIT));
    }
    else
    {
      System.out.println("Process " + getPid() + " downs crit mutex");
      mem.setCrit(false);
    }
  }

  private void upEmpty()
  {
    System.out.println("Process " + getPid() + " ups empty mutex");
    mem.setEmpty(true);
  }

  private void upCrit()
  {
    System.out.println("Process " + getPid() + " ups crit mutex");
    mem.setCrit(true);
  }
}
